package common

import (
	"errors"
	"fmt"
)

type LinkedStack struct {
	Head *LNode
}

// IsEmpty 检查栈是否为空
func (p *LinkedStack) IsEmpty() bool {
	return p.Head.Next == nil
}

// Size 查看栈中元素个数
func (p *LinkedStack) Size() int {
	size := 0
	node := p.Head.Next
	for node != nil {
		size++
		node = node.Next
	}
	return size
}

// Push 入栈
func (p *LinkedStack) Push(e int) {
	p.Head.Next = &LNode{
		Data: e,
		Next: p.Head.Next,
	}
}

// Pop 出栈
func (p *LinkedStack) Pop() int {
	current := p.Head.Next
	if current != nil {
		p.Head.Next = current.Next
		return current.Data
	}
	panic(errors.New("栈已经空了"))
}

// Top 查看栈顶元素
func (p *LinkedStack) Top() int {
	if p.Head.Next != nil {
		return p.Head.Next.Data
	}
	panic(errors.New("栈已经空了"))
}

func NewLinkedStack() *LinkedStack {
	return &LinkedStack{
		Head: &LNode{},
	}
}

func CreateStack(list []int) *LinkedStack {
	stack := &LinkedStack{
		Head: &LNode{},
	}
	for _, value := range list {
		stack.Push(value)
	}
	return stack
}

func PrintStack(stack *LinkedStack) {
	if stack == nil || stack.Head == nil {
		return
	}
	current := stack.Head.Next
	for current != nil {
		fmt.Print(current.Data, " ")
		current = current.Next
	}
	fmt.Println()
}
